package gov.fgn.sijyp.web.filter;


import gov.fgn.sijyp.general.exception.SIJYPLogOutNonexistentConversationException;

import java.io.IOException;
import java.security.Principal;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.enterprise.context.NonexistentConversationException;
import javax.faces.context.FacesContext;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContexts;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

@PersistenceContexts({
	//@PersistenceContext(unitName ="fiscalia", name="persistence/fiscaliaEm"),
	@PersistenceContext(unitName ="default", name="persistence/defaultEm")
})
public class ConnectionFilter implements Filter {
 
	private static final Logger LOG = Logger.getLogger(ConnectionFilter.class.getName());
    @Resource
    private UserTransaction utx;
    
    
    @Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpSession session = null;
		HttpServletRequest httpRequest = null;
		HttpServletResponse res = null;
		try {
			httpRequest = (HttpServletRequest) request;
			res = (HttpServletResponse) response;
			Principal principal = httpRequest.getUserPrincipal();
			session = httpRequest.getSession(false);
			
			if (principal != null) {
				utx.begin();
				chain.doFilter(request, response);
				utx.commit();
			}
		} catch (NonexistentConversationException e) {
			
			LOG.severe(e.getMessage());
			
			ServletContext context = httpRequest.getServletContext();			
			context.setAttribute("GLO", "true");
			
			throw new SIJYPLogOutNonexistentConversationException(e);

		} catch ( IllegalStateException e ){
			
			LOG.severe(e.getMessage());
			
			try {        		
				utx.rollback();
			} catch (IllegalStateException ex) {
				LOG.severe(ex.getMessage());
			} catch (SystemException ex) {
				LOG.severe(ex.getMessage());
			}
			
		} catch (SystemException e){
			
			LOG.severe(e.getMessage());
			
			try {        		
				utx.rollback();
			} catch (IllegalStateException ex) {
				LOG.severe(ex.getMessage());
			} catch (SystemException ex) {
				LOG.severe(ex.getMessage());
			}
			
		} catch (NotSupportedException e) {
			
			LOG.severe(e.getMessage());
			
			try {        		
				utx.rollback();
			} catch (IllegalStateException ex) {
				LOG.severe(ex.getMessage());
			} catch (SystemException ex) {
				LOG.severe(ex.getMessage());
			}
			
		} catch (SecurityException e) {
			
			LOG.severe(e.getMessage());
			
			try {        		
				utx.rollback();
			} catch (IllegalStateException ex) {
				LOG.severe(ex.getMessage());
			} catch (SystemException ex) {
				LOG.severe(ex.getMessage());
			}
			
		} catch (RollbackException e) {
			LOG.severe(e.getMessage());
			
			try {        		
				utx.rollback();
			} catch (IllegalStateException ex) {
				LOG.severe(ex.getMessage());
			} catch (SystemException ex) {
				LOG.severe(ex.getMessage());
			}
			
		} catch (HeuristicMixedException e) {
			
			LOG.severe(e.getMessage());
			
			try {        		
				utx.rollback();
			} catch (IllegalStateException ex) {
				LOG.severe(ex.getMessage());
			} catch (SystemException ex) {
				LOG.severe(ex.getMessage());
			}
			
		} catch (HeuristicRollbackException e) {
			LOG.severe(e.getMessage());
			
			try {        		
				utx.rollback();
			} catch (IllegalStateException ex) {
				LOG.severe(ex.getMessage());
			} catch (SystemException ex) {
				LOG.severe(ex.getMessage());
			}

		}
	}
    
    /*    private ServletContext context;
    
    @Inject
    private IPermisoSession permiso;*/
 
    /*@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    	try {
    		HttpServletRequest httpRequest = (HttpServletRequest) request;

    		HttpServletResponse res = (HttpServletResponse) response;
    		
    		Principal principal = httpRequest.getUserPrincipal();

    		String uri = httpRequest.getRequestURI();
    		this.context.log("Requested Resource::"+uri);
    		HttpSession session = httpRequest.getSession(false);

    		if(session == null && !(uri.endsWith("xhtml"))){
    			this.context.log("Unauthorized access request");
    			res.sendRedirect("/sijyp/blank.xhtml");

    			    			
    		}else if(!permiso.verificarAccesoVista(principal.getName(), uri)){
				this.context.log("Unauthorized access request");
    			res.sendRedirect("/sijyp/blank.xhtml");

			}
    		else{

    		
    			if(principal != null) {
    				utx.begin();
    				chain.doFilter(request, response);
    				utx.commit();


    			}
    		}
    	} catch (Exception e) {
    		LOG.severe(e.getMessage());
    		e.printStackTrace();
    		try {
    			utx.rollback();
    		} catch (IllegalStateException ex) {
    			ex.printStackTrace();
    			LOG.severe(ex.getMessage());
    		} catch (SystemException ex) {
    			ex.printStackTrace();
    			LOG.severe(ex.getMessage());
    		}
    	}
    }*/
 
    
    private HttpSession getSession() {
        return (HttpSession) FacesContext.
                getCurrentInstance().
                getExternalContext().
                getSession(false);
    }
    
    @Override
    public void init(FilterConfig fConfig) throws ServletException {
    	 //this.context = fConfig.getServletContext();
    }
    
    @Override
    public void destroy() {
 
    }
}
